﻿using BMCW.Infrastructure.Entity;
using BMCW.Infrastructure.Service;
using BMCW.Utility;
using BMCW.Utility.Logging;
using YouWei.Winform.Common;
using YouWei.Winform.Model;
using mshtml;
using Newtonsoft.Json;
using RestSharp;
using Standard.Infrastructure.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YouWei.Winform
{
    /// <summary>
    /// IE浏览器
    /// </summary>
    public partial class FrmMainNew : Form
    {
        DCDrivingQueryService queryService = new DCDrivingQueryService();
        DCInterfaceLogService logService = new DCInterfaceLogService();
        DiyaDistributorInterfaceService interfaceService = new DiyaDistributorInterfaceService();

        protected DCDrivingQuery DrivingQuery = new DCDrivingQuery();   //当前查询
        protected string Base122Url = "https://bj.122.gov.cn";
        protected Dictionary<string, string> ProDic = new Dictionary<string, string>();

        protected int TimerCount = 0;  //默认三次失败就是失败
        protected int ImageCount = 0;  //验证码加载错误次数 超过3次就默认识别
        protected string Capcha = "";   //当前验证码

        //cookie缓存
        protected CookieContainer ck = new CookieContainer();

        public FrmMainNew()
        {
            InitializeComponent();
            wbRight.ScriptErrorsSuppressed = true;
            wbRight.Url = new Uri(Base122Url + "/views/inquiry.html");
        }

        #region 浏览器

        /// <summary>
        /// 浏览器初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            ((WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

            GetCookies(wbRight.Url.ToString());

            timer2.Start();
        }

        /// <summary>
        /// 重写错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            //忽略该错误并抑制错误对话框 
            e.Handled = true;
        }

        /// <summary>
        /// 获取地址
        /// </summary>
        /// <param name="url"></param>
        private void GetCookies(string url)
        {
            ck = new CookieContainer();
            string cookie = CookieReader.GetCookie(url);
            if (!string.IsNullOrEmpty(cookie))
            {
                string[] strs = cookie.Split(new char[] { ';' });
                foreach (var item in strs)
                {
                    string[] strs1 = item.Split(new char[] { '=' });
                    var cke = new Cookie(strs1[0].Trim(), strs1[1].Trim())
                    {
                        Domain = wbRight.Document.Url.Host,
                        Expired = false,
                        Expires = DateTime.Now.AddDays(1),
                        HttpOnly = true
                    };
                    ck.Add(cke);
                }
            }
        }

        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            InitDic();
        }

        /// <summary>
        /// 请求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PostData()
        {
            //{"message":"操作成功！","data":{"ljjf":"0"},"code":200}
            ApiResult rt = RequestHelper.PostHtml(Base122Url + "/m/publicquery/scores", "jszh=" + DrivingQuery.DirvingLicense + "&dabh=" + DrivingQuery.DocumentCode + "&captcha=" + Capcha + "&qm=wf&page=1", Encoding.UTF8, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36", ck);
            if (rt.status == 0)
            {
                JJ122Model model = JsonConvert.DeserializeObject<JJ122Model>(rt.message);
                if (model.code == 200)
                {
                    short result = 0;
                    short.TryParse(model.data.ljjf, out result);
                    DrivingQuery.QueryResult = result;
                    DrivingQuery.QueryStatus = 1;
                    DrivingQuery.QueryEndTime = DateTime.Now;
                    DrivingQuery.QueryData = rt.message;
                    queryService.Update(DrivingQuery);

                    interfaceService.UpdateBalanceByDistributorId(DrivingQuery.DistributorId, "DrivingQuery/DrivingScoreQuery");
                    TimerCount = 0;
                }
                else
                {
                    if (model.message.StartsWith("图片验证码"))
                    {
                        if (TimerCount >= 2)
                        {
                            TimerCount = 0;
                            DrivingQuery.QueryResult = -1;
                            DrivingQuery.QueryStatus = 2;
                            DrivingQuery.QueryEndTime = DateTime.Now;
                            DrivingQuery.QueryData = model.message;
                            queryService.Update(DrivingQuery);
                        }
                        else
                        {
                            TimerCount++;
                        }
                    }
                    else
                    {
                        TimerCount = 0;
                        DrivingQuery.QueryResult = -1;
                        DrivingQuery.QueryStatus = 1;
                        DrivingQuery.QueryEndTime = DateTime.Now;
                        DrivingQuery.QueryData = model.message;
                        queryService.Update(DrivingQuery);
                    }
                }
            }
            else {
                if (TimerCount >= 3)
                {
                    TimerCount = 0;
                    DrivingQuery.QueryResult = -1;
                    DrivingQuery.QueryStatus = 2;
                    DrivingQuery.QueryEndTime = DateTime.Now;
                    DrivingQuery.QueryData = "查询失败";
                    queryService.Update(DrivingQuery);
                }
                else
                {
                    TimerCount++;
                }
            }
            timer2.Start();
        }

        /// <summary>
        /// 定时查询数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer2_Tick(object sender, EventArgs e)
        {
            DrivingQuery = queryService.GetFirstNoRun();
            if (DrivingQuery != null)
            {
                timer2.Stop();
                foreach (var kvp in ProDic)
                {
                    if (DrivingQuery.DocumentCode.StartsWith(kvp.Key))
                    {
                        string url = "https://" + kvp.Value + ".122.gov.cn";
                        if (url != Base122Url)
                        {
                            Base122Url = url;
                            wbRight.Url = new Uri(Base122Url);
                            break;
                        }
                        else
                        {
                            CaptchaLoad();
                            break;
                        }
                    }
                }
            }
        }

        #region 验证码识别

        /// <summary>
        /// 验证码识别
        /// </summary>
        /// <param name="drvNo"></param>
        /// <param name="dnNo"></param>
        protected void CaptchaLoad()
        {
            string str = "";
            var rt = RequestHelper.GetFile(Base122Url + "/captcha?nocache=" + DateTime.Now.Ticks, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36", ck);
            if (rt.status == 1 && rt.bytes.Length > 0)
            {
                str = Convert.ToBase64String(rt.bytes);
            }
            else
            {
                ImageCount++;
                if (ImageCount >= 2)
                {
                    DrivingQuery.QueryResult = -1;
                    DrivingQuery.QueryStatus = 2;
                    DrivingQuery.QueryEndTime = DateTime.Now;
                    DrivingQuery.QueryData = rt.message;
                    queryService.Update(DrivingQuery);
                }
            }
            ImageCount = 0;
            if (CaptchOCR(str))
            {
                PostData();
            }

            if (string.IsNullOrEmpty(str))
            {
                timer2.Start();
                return;
            }
            ImageCount = 0;
            //获取验证码
            if (CaptchOCR(str))
            {
                PostData();
            }
        }

        /// <summary>
        /// 验证码识别
        /// </summary>
        /// <param name="str"></param>
        private bool CaptchOCR(string str)
        {
            bool rtq = true;

            RestClient restClient = new RestClient("https://v2-api.jsdama.com")
            {
                UserAgent = UserAgentConst.GetUserAgent()
            };
            RestRequest request = new RestRequest("/upload", Method.POST);

            request.AddHeader("Host", "v2-api.jsdama.com");
            request.AddHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            request.AddHeader("Content-Type", "text/json");
            var model = new JsdamaModel
            {
                captchaData = str
            };
            request.AddJsonBody(model);
            IRestResponse response = null;
            try
            {
                request.AddJsonBody(model);
                response = restClient.Execute(request);

                var rt = JsonConvert.DeserializeObject<JsDamaResultModel>(response.Content);
                if (rt.code == 0)
                {
                    Capcha = rt.data.recognition;
                    //定时轮询
                    timer2.Stop();
                }
                else
                {
                    timer2.Start();
                    rtq = false;
                }
            }
            catch (Exception ex)
            {
                Error(ex, "https://v2-api.jsdama.com/upload");
                timer2.Start();
                rtq = false;
            }

            logService.Insert(new DCInterfaceLog()
            {
                APIPath = "https://v2-api.jsdama.com/upload",
                ResponseResult = response == null ? "" : response.Content,
                RequestParm = "",
                ResponseStatus = -1,
                CallSource = 5,
                RequestDate = DateTime.Now,
                ResponseDate = DateTime.Now
            });
            return rtq;
        }

        #endregion

        private void Error(Exception ex, string url)
        {
            logService.Insert(new DCInterfaceLog()
            {
                ResponseResult = ex.Message,
                RequestParm = ex.Source,
                ResponseStatus = -1,
                CallSource = 5,
                APIPath = url,
                RequestDate = DateTime.Now,
                ResponseDate = DateTime.Now
            });
        }

        private void InitDic()
        {
            ProDic.Add("11", "bj");
            ProDic.Add("12", "tj");
            ProDic.Add("13", "he");
            ProDic.Add("14", "sx");
            ProDic.Add("15", "nm");
            ProDic.Add("21", "ln");
            ProDic.Add("22", "jl");
            ProDic.Add("23", "hl");
            ProDic.Add("31", "sh");
            ProDic.Add("34", "ah");
            ProDic.Add("35", "fj");
            ProDic.Add("36", "jx");
            ProDic.Add("37", "sd");
            ProDic.Add("41", "ha");
            ProDic.Add("42", "hb");
            ProDic.Add("43", "hn");
            ProDic.Add("44", "gd");
            ProDic.Add("45", "gx");
            ProDic.Add("46", "hi");
            ProDic.Add("50", "cq");
            ProDic.Add("51", "sc");
            ProDic.Add("52", "gz");
            ProDic.Add("53", "yn");
            ProDic.Add("54", "xz");
            ProDic.Add("61", "sn");
            ProDic.Add("62", "gs");
            ProDic.Add("63", "qh");
            ProDic.Add("64", "nx");
            ProDic.Add("65", "xj");

            ProDic.Add("3201", "nkg");
            ProDic.Add("3202", "wux");
            ProDic.Add("3203", "xuz");
            ProDic.Add("3204", "czx");
            ProDic.Add("3205", "szv");
            ProDic.Add("3206", "ntg");
            ProDic.Add("3207", "lyg");
            ProDic.Add("3208", "has");
            ProDic.Add("3209", "ynz");
            ProDic.Add("3210", "yzo");
            ProDic.Add("3211", "zhe");
            ProDic.Add("3212", "tzs");
            ProDic.Add("3213", "suq");

            ProDic.Add("3301", "hgh");
            ProDic.Add("3302", "ngb");
            ProDic.Add("3303", "wnz");
            ProDic.Add("3304", "jix");
            ProDic.Add("3305", "hzh");
            ProDic.Add("3306", "sxg");
            ProDic.Add("3307", "jha");
            ProDic.Add("3308", "quz");
            ProDic.Add("3309", "zos");
            ProDic.Add("3310", "tzz");
            ProDic.Add("3311", "lss");
        }

    }
}
